<template>
  <div>
    <!--    <el-form-item-->
    <!--      label="选项分隔符"-->
    <!--    >-->
    <!--      <el-input-->
    <!--        v-model="activeData.separator"-->
    <!--        placeholder="请输入选项分隔符"-->
    <!--      />-->
    <!--    </el-form-item>-->

    <!--          <el-FormItem-item-->
    <!--            v-if="activeData.config.tag === 'el-cascader'"-->
    <!--            label="任选层级"-->
    <!--          >-->
    <!--            <el-switch v-model="activeData.props.props.checkStrictly" />-->
    <!--          </el-FormItem-item>-->
    <!--    <el-form-item-->
    <!--      label="是否多选"-->
    <!--    >-->
    <!--      <el-switch v-model="activeData.props.props.multiple" />-->
    <!--    </el-form-item>-->
    <el-form-item :label="$t('formgen.cascader.showAll')">
      <el-switch v-model="activeData['show-all-levels']" />
    </el-form-item>
    <el-form-item :label="$t('formgen.cascader.search')">
      <el-switch v-model="activeData.filterable" />
    </el-form-item>
    <el-divider>{{ $t("formgen.option.optionSet") }}</el-divider>
    <el-radio-group
      v-model="activeData.config.optionsType"
      size="default"
    >
      <el-radio-button :value="0">{{ $t("formgen.option.staticData") }}</el-radio-button>
      <el-radio-button :value="1">{{ $t("formgen.option.dynamic") }}</el-radio-button>
    </el-radio-group>

    <!-- 远程赋值配置 -->
    <div v-if="activeData.config.optionsType === 1">
      <el-input
        v-model="activeData.config.dynamicOptions.url"
        placeholder="https://api.xxxx.com/xxx.json"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.url") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.dataPath"
        placeholder="data"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.listPath") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.valueField"
        placeholder="value"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.value") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.labelField"
        placeholder="label"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.label") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.childrenField"
        placeholder="chidren"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.cascader.childOption") }}</template>
      </el-input>
    </div>

    <div v-else>
      <!-- 级联选择静态树 -->
      <el-tree
        :data="treeData"
        :expand-on-click-node="false"
        default-expand-all
        node-key="id"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="node-operation">
              <el-icon
                v-if="data.level < 4"
                @click="append(data)"
              >
                <ele-Plus />
              </el-icon>
              <el-icon @click="editNode(data)">
                <ele-Edit />
              </el-icon>
              <el-icon
                class="text-danger"
                @click="remove(node, data)"
              >
                <ele-Delete />
              </el-icon>
            </span>
          </div>
        </template>
      </el-tree>
      <div style="margin-left: 20px">
        <el-button
          icon="ele-CirclePlus"
          link
          style="padding-bottom: 0"
          type="primary"
          @click="addTreeItem"
        >
          {{ $t("formgen.option.addOption") }}
        </el-button>
        <el-button
          icon="ele-DocumentCopy"
          link
          type="primary"
          @click="batchEditTreeItem"
        >
          {{ $t("formgen.option.batchAdd") }}
        </el-button>
        <el-button
          icon="ele-DocumentCopy"
          link
          type="primary"
          @click="openCascaderBatchEdit"
        >
          {{ $t("formgen.option.batchEdit") }}
        </el-button>
      </div>
      <el-divider />
    </div>
    <treeNode-dialog
      v-model:visible="dialogVisible"
      :edit-data="editingNode"
      :title="editingNode ? $t('common.edit') : $t('formgen.option.addOption')"
      @commit="addNode"
    />
    <el-dialog
      v-model="batchDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="$t('formgen.option.batchAdd')"
    >
      <batch-treeNode-dialog
        v-if="batchDialogVisible"
        ref="batchAddRef"
        :tree-data="treeData"
        @close="batchAddNode"
      />
      <template #footer>
        <div>
          <el-button
            size="default"
            @click="batchDialogVisible = false"
          >
            {{ $t("formI18n.all.cancel") }}
          </el-button>
          <el-button
            size="default"
            type="primary"
            @click="handelConfirm"
          >
            {{ $t("formI18n.all.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="cascaderBatchEditVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="$t('formgen.option.batchEdit')"
      width="80%"
    >
      <cascader-batch-edit
        v-if="cascaderBatchEditVisible"
        :tree-data="treeData"
        @cancel="cascaderBatchEditVisible = false"
        @close="handleCascaderBatchEdit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import CascaderBatchEdit from "./cascader/CascaderBatchEdit.vue";
import BatchTreeNodeDialog from "./cascader/BatchTreeNodeDialog.vue";
import TreeNodeDialog from "./cascader/TreeNodeDialog.vue";

import { computed, ref } from "vue";
import _cloneDeep from "lodash-es/cloneDeep";
import { get, isArray } from "lodash-es";
import { execRemoteAPI } from "@/views/formgen/api/execRemoteAPI";

// props 定义
const props = defineProps(["activeData"]);

// 响应式状态
const dialogVisible = ref(false);
const batchDialogVisible = ref(false);
const cascaderBatchEditVisible = ref(false);
const isEdit = ref(false);
const editingNode = ref(null);
const currentNode = ref(null);
const batchAddRef = ref(null); // 用于模板引用

// 计算属性
const treeData = computed(() => {
  const { options } = props.activeData.config;

  const handelData = (list, index, id) => {
    list.forEach(item => {
      item.level = index;
      item.parentId = id || 0;
      if (item.children && item.children.length) {
        handelData(item.children, index + 1, item.id);
      }
    });
    return list;
  };
  return handelData(_cloneDeep(options), 1);
});

// 方法
const handleReQueryOptionsData = async () => {
  const config = props.activeData.config;
  let finalOptions = [];
  if (config.optionsType && config.optionsType === 1) {
    execRemoteAPI.get(config.dynamicOptions.url).then(res => {
      const options = get(res, config.dynamicOptions.dataPath);
      if (options && isArray(options)) {
        const dyOptions = options.map(op => ({
          value: get(op, config.dynamicOptions.valueField),
          label: get(op, config.dynamicOptions.labelField),
          children: get(op, config.dynamicOptions.childrenField)
        }));
        finalOptions = dyOptions;
      }
    });
  }
  props.activeData.config.options = finalOptions;
};

const addNode = data => {
  if (isEdit.value) {
    editingNode.value.label = data.label;
    props.activeData.config.options = _cloneDeep(treeData.value);
    isEdit.value = false;
    editingNode.value = null;
  } else {
    currentNode.value.push(data);
    props.activeData.config.options = _cloneDeep(treeData.value);
  }
};

const batchAddNode = data => {
  props.activeData.config.options.push(..._cloneDeep(data));
  batchDialogVisible.value = false;
};

const addTreeItem = () => {
  dialogVisible.value = true;
  currentNode.value = props.activeData.config.options;
  isEdit.value = false;
  editingNode.value = null;
};

const append = data => {
  if (!data.children) {
    data.children = [];
  }
  dialogVisible.value = true;
  currentNode.value = data.children;
  isEdit.value = false;
  editingNode.value = null;
};

const remove = (node, data) => {
  props.activeData.config.defaultValue = []; // 避免删除时报错
  const { parent } = node;
  const children = parent.data.children || parent.data;
  const index = children.findIndex(d => d.id === data.id);
  children.splice(index, 1);
  props.activeData.config.options = _cloneDeep(treeData.value);
};

const batchEditTreeItem = () => {
  batchDialogVisible.value = true;
};

const handelConfirm = () => {
  batchAddRef.value.handleConfirm();
};

const editNode = data => {
  console.log(data);
  isEdit.value = true;
  editingNode.value = data;
  dialogVisible.value = true;
};

const openCascaderBatchEdit = () => {
  cascaderBatchEditVisible.value = true;
};

const handleCascaderBatchEdit = data => {
  props.activeData.config.options = _cloneDeep(data);
  cascaderBatchEditVisible.value = false;
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-operation {
  .el-icon {
    margin-left: 8px;
    cursor: pointer;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>
